from typing import Optional
from PySide6.QtCore import QObject, QThread, qDebug, Signal, QTimer, QMutex
from Libs.Jinritemai.Spider import Jinritemai
import math, time
from . import *


class JinritemaiThread(QObject):
    finished = Signal()
    resp = Signal(list)
    darenListResp = Signal(list, int, int, float)
    darenContactResp = Signal(dict)

    def __init__(self, parent=None, *args, **kwargs):
        super(JinritemaiThread, self).__init__(parent)
        self.cookies = kwargs.get('cookies', '')
        self.screenInfo = kwargs.get('screenInfo', '')
        self.verifyFp = kwargs.get('verifyFp', '')
        self.msToken = kwargs.get('msToken', '')
        self.ua = kwargs.get('ua', '')
        self.body = kwargs.get('body', {})
        self.darenUids = kwargs.get('darenUids', [])
        self.contactMode = kwargs.get('contactMode', 1)
        self.s = None
        self.contactLimit = kwargs.get('contactLimit', 100)

        self.is_pause = False
        self.is_close = False

        self.contact_close = False

    def pause(self):
        """
        暂停了采集程序
        """
        self.is_pause = True

    def resume(self):
        """
        继续采集程序
        """
        self.is_pause = False

    def close(self):
        """
        关闭采集程序
        """
        self.is_close = True

    def closeContact(self):
        self.contact_close = True

    def initJinritemai(self):
        self.s = Jinritemai()
        self.s.cookies = self.cookies
        self.s.verifyFp = self.verifyFp
        self.s.msToken = self.msToken
        self.s.ua = self.ua
        self.s.screenInfo = self.screenInfo

    def getDarenContactInfoViaManager(self):
        qDebug(f'JinritemaiThread running(add daren manager)')
        qDebug(f'self.s: {self.s}')
        if not self.s or isinstance(self.s, Jinritemai):
            self.initJinritemai()
        
        times = 0
        logging.info(f'bbbbb: {self.darenUids}')
        darenUids = list(self.darenUids.keys())
        while not self.contact_close:
            if not len(darenUids):
                logging.error(f'采集完毕, 结束循环: {len(darenUids)}')
                break

            uid = darenUids.pop(0)
            if times == self.contactLimit:
                self.darenContactResp.emit({'uid': uid, 'contactInfo': None})
                break
            darenInfo = self.darenUids.get(uid, None)
            if not darenInfo:
                continue
            
            add2DarenManager = self.s.addDarenManage(uid=uid)
            logging.info(f'添加达人到达人库结果: {add2DarenManager}')
            time.sleep(1.0)

            dy_id = darenInfo.get('dy_id', '')
            authorList = self.s.getDarenFromManager(dy_id=dy_id)
            if not authorList:
                logging.error(f'采集{dy_id}时, 没有从达人库中获取到数据: {authorList}')
                continue
            author = authorList[0]
            logging.info(f'author: {author}')
            new_uid = author.get('author', {}).get('uid', None)
            if not new_uid:
                logging.error(f'采集{dy_id}时, 返回结果里没有拿到uid')
                continue
            else:
                time.sleep(1.0)

            nickname = darenInfo.get('nickname')
            contactInfo = self.s.getDarenContactInfo(uid=new_uid, mode=self.contactMode, nickname=nickname)
            logging.info(f'darenContactInfo: {contactInfo}')    
            self.darenContactResp.emit({'uid': uid, 'contactInfo': contactInfo})
            if contactInfo == '达人未绑定此联系方式或权限不足':
                logging.error(f'采集结果拿到: {contactInfo}')
                continue
            elif contactInfo is None:
                times += 1
                logging.error(f'采集结果拿到None: {contactInfo}')
                # self.darenContactResp.emit({'uid': uid, 'contactInfo': None})
                break
            elif contactInfo is False:
                logging.error(f'采集达人信息时拿到false: {contactInfo}')
                continue
            times += 1
            time.sleep(1.0)
        else:
            logging.info(f'停止了采集达人联系方式线程')
        self.finished.emit()

    def getDarenContactInfo(self):
        """
        启动获取达人联系方式线程
        """
        times = 0
        qDebug(f'JinritemaiThread running(daren contact)')
        if not self.s or isinstance(self.s, Jinritemai):
            self.initJinritemai()
        darenUids = list(self.darenUids.keys())
        while not self.is_close:
            if self.is_pause:
                continue
            if not len(darenUids):
                logging.error(f'没有需要采集的达人uid: {len(darenUids)}')
                break

            uid = darenUids.pop(0)
            if times == self.contactLimit:
                self.darenContactResp.emit({'uid': uid, 'contactInfo': None})
                break

            nickname = self.darenUids.get(uid, None)
            contactInfo = self.s.getDarenContactInfo(uid=uid, mode=self.contactMode, nickname=nickname)
            # 测试专用
            # contactInfo = {"uid": 123, "contactInfo": {"contact_info": {"mobile": "123", "times_left": 1}}}
            self.darenContactResp.emit({'uid': uid, 'contactInfo': contactInfo})
            if contactInfo is None:
                times += 1
                logging.error(f'采集结果拿到None: {contactInfo}')
                # self.darenContactResp.emit({'uid': uid, 'contactInfo': None})
                break
            elif contactInfo is False:
                logging.error(f'采集达人信息时拿到false: {contactInfo}')
                continue
            times += 1
            time.sleep(1.0)
        else:
            logging.info(f'停止了采集程序')
        self.finished.emit()

    def getDarenList(self):
        qDebug(f'JinritemaiThread running(daren list)')
        data = []
        if not self.s or isinstance(self.s, Jinritemai):
            self.initJinritemai()
        qDebug(f'jinritemaiThread daren list data: {data}')
        page, pages, total, sleepTime, darenList = self.body.get('page', 1), 2, 20, 2.0, []
        logging.debug(f'page: {page}, pages: {pages}, res: {page <= pages}')
        # while page <= pages:
        while not self.is_close:
            if self.is_pause:
                # logging.debug(f"暂停了，不采集")
                continue
            # logging.debug(f"aaaaa")
            # 设置request的body
            self.s.body = self.body
            # 当当前页大于第一页时，refresh设置为False
            if page > 1:
                self.s.body['page'] = page
                self.s.body['refresh'] = False
            logging.debug(f'daren list threading body: {self.s.body}')

            data = self.s.getDarenList()

            # 判断总共采集几次达人列表页数据
            if data.get('has_more', False):
                total = data.get('total', 2000)
            total = total if total < self.contactLimit else self.contactLimit
            logging.debug(f'total: {total} - {self.contactLimit}')

            darenList = data.get('list', [])
            if not darenList:
                pages = 0
                break
            self.darenListResp.emit(darenList, page, total, sleepTime)

            pages = math.ceil(total / len(darenList))
            page += 1
            self.is_close = not page <= pages
            time.sleep(sleepTime)
        else:
            logging.info(f'停止了采集程序')

        self.finished.emit()


    def getSearchFilter(self):
        qDebug(f'JinritemaiThread running(search filters)')
        data = []
        if not self.s or isinstance(self.s, Jinritemai):
            self.initJinritemai()
        data = self.s.getSearchFilter()
        self.resp.emit(data)
        self.finished.emit()

    
